<?php
include 'AdminController.php';
class Admin_CsvController extends Admin_AdminController{
   public function init(){
    	//Sử dụng admin layout
        $layoutPath = APPLICATION_PATH . '/templates/admin/admin';
        $option = array('layout' => 'index', 'layoutPath' => $layoutPath);
        Zend_Layout::startMvc($option);
        
        //アクティブメニューを設定
        $this->view->active_menu = "csv";
   }
  public function indexAction(){
   		Zend_Loader::loadClass("CSVModel");
    	Zend_Loader::loadClass("OrderModel");
    	Zend_Loader::loadClass("AuthModel");
    	
    	$request = $this->getRequest();
    	$view = $this->view;
    	
    	//TODO 作成ユーザ情報を
    	$auth = new AuthModel();
    	$create_user_id = $auth->getUserInfo("username");
    	$create_user_name = $auth->getUserInfo("name");
    	
    	//TODO: パラメータを取得
    	$date = $request->getParam("date");
    	if(!$date){
    		$date = strtotime("- 1 month", strtotime(date("Y-m")));
    		$date = date('Y-m', $date);
    	}
    	$view->date = $date;
    	
    	//TODO スタートタイムとエンドタイムを計算
    	$arr = $this->getYearAndMonth($date);
    	$year = $arr['year'];
    	$month = $arr['month'];
    		
    	if($request->isPost()){
	    	//TODO ユーザの予約の一覧を読み出すためにオーだモデルのインスタンスを作成する
	    	$model = new CSVModel();
	    	$data = $model->getCSVData($year, $month);
	    	$output_filename = $year . "年" . $month . "月" . ".csv";
	    	
	    	//TODO HTMLコードを削除する
	    	$this->_helper->layout->disableLayout();
	   	    $this->_helper->viewRenderer->setNoRender();
	    	
	   	    //TODO CSVファイルを保存する
			header ( "Expires:". gmdate ( "D,d M Y - H:i:s" ) . " GMT"  );
			header ( "Cache-Control: no-cache, must-revalidate" );
			header ( "Pragma: no-cache" );
			header ("Content-type: application/octet-stream");
			header ("Content-Disposition: attachment; filename=\"$output_filename\"");
			header ( "Content-Description: 予約データ" );
			
			//TODO データ作成
			//TODO ファイルのヘッダー
			echo PAYMENT_SYSTEM_ID . ",";
			echo $year . "," . $month . ",";
			echo date("Y") . "," . date("m") . "," .date("d") . "," . date("H") . "," . date('m') . "," . date("j") . ",";
			echo $create_user_id . "," . $create_user_name . "\n";
			
			//TODO 請求データ 
			foreach ($data as $row){
				
				echo $row['username'] . "," . $row['name'] . ",";
				echo ($row['total_money'] + $row['total_fee']) . "," . $row['address'] . "," . $row['phone'] . "\n";
			}
			
			//TODO ファイルフォーたー
			echo "END____END___END" . "," . $year . "," . $month . "\n";
		}	
		
		//TODO Navigator を設定
    	$nav['ホーム'] = "/admin";
    	$nav['CSV'] = "/admin/CSV";
    	$view->nav = $nav;
  }
  
	function getYearAndMonth($date_str){
    	$arr['year'] = substr($date_str, 0, 4);
    	$arr['month'] = substr($date_str,5);
    	
    	return $arr;
    }
}
?>